﻿using ChatJs.Net;
using DataMongo;
using MVCMongo.Code;
using MVCMongo.Code.LongPolling.Chat;
using MVCMongo.Code.SignalR;
using DataMongo.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCMongo.Services;
using MVCMongo.ViewModel;
using WebMatrix.WebData;


namespace MVCMongo.Controllers
{
    [Authorize]
    public class GroupController : Controller
    {
        private int userId = WebSecurity.GetUserId(WebSecurity.CurrentUserName);
        //
        // GET: /Group/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Group(int groupId)
        {
            var connection = new RepositoryBaseMongo("Group");
            var connectM = new RepositoryBaseMongo("GroupMember");
            var list = connectM.GetAll<GroupMember>().Where(x => x.GroupId == groupId).Select(x => x.MemberID);
            var data = connection.GetAll<Group>().FirstOrDefault(x => x.GroupId==groupId);
            var firstList = UtilityService.GetFriendList();
            var notGroupfriend = firstList.Where(x => !list.Contains(x)).ToList();
            ViewBag.FriendList = notGroupfriend;

            var existingUser = ChatHelper.GetChatUserFromCookie(this.Request);
            if (existingUser != null)
            {
                if (!ChatHub.IsUserRegistered(existingUser))
                {
                    // cookie is invalid
                    ChatHelper.RemoveCookie(this.Response);
                    return this.RedirectToAction("Group");
                }
            }
            var viewModel = new ProfileIndexViewModel();
            viewModel.Group = data;
            viewModel.ChatModel = null;
            viewModel.PostType = "1";
            var user = new ChatUser()
            {
                Name = WebSecurity.CurrentUserName,
                Email = WebSecurity.CurrentUserName,
                ProfilePictureUrl = WebSecurity.CurrentUserName,
                Id = new Random().Next(100000),
                Status = ChatUser.StatusType.Online,
                RoomId = ChatController.ROOM_ID_STUB
            };

            // for signalr
            {
                ChatHub.RegisterNewUser(user);
            }

            // for long-polling
            {
                ChatServer.SetupRoomIfNonexisting(ChatController.ROOM_ID_STUB);
                ChatServer.Rooms[ChatController.ROOM_ID_STUB].RegisterNewUser(user);
            }
            ChatHelper.CreateNewUserCookie(this.Response, user);
            // in this case the authentication cookie is valid and we must render the chat
            viewModel.ChatModel = new ChatViewModel()
            {
                IsUserAuthenticated = true,
                UserId = userId,
                UserName = WebSecurity.CurrentUserName,
                UserProfilePictureUrl = WebSecurity.CurrentUserName
            };

            return View(viewModel);

        }

        public ActionResult MemberList(int groupId)
        {

            var connection = new RepositoryBaseMongo("GroupMember");
            var data = connection.GetAll<GroupMember>().Where(x => x.GroupId == groupId).ToList();
            return PartialView(data);
        }
        public ActionResult CreateGroup()
        {
           
            var conn = new RepositoryBaseMongo("FriendList");
            var list = conn.GetAll<FriendList>().Where(x => x.MyId == userId || x.FriendId==userId).ToList();
            var group = new Group()
            {
                Type = "close"
            };
           
       
            ViewBag.FriendList = new SelectList(list, "MyId", "FriendId");
            return View(group);

        }

        [HttpPost]
        public ActionResult CreateGroup(Group group, List<int> member)
        {
            if (ModelState.IsValid)
            {
                var connection = new RepositoryBaseMongo("Group");
                int Id = 0;
                var Groups = connection.GetAll<Group>().ToList();
                if (Groups.Any())
                    Id = Groups.Max(x => x.GroupId);
                    Id += 1;
                    group.GroupId = Id;
                    connection.InsertOrUpdate(group);

                // members post
                    var conM = new RepositoryBaseMongo("GroupMember");
                    var members = new GroupMember();
                members.GroupId = Id;
                members.IsAdmin = true;
                members.MemberID = userId;
                members.JoinDate = DateTime.UtcNow;
                conM.InsertOrUpdate(members);
               
                    
                  
                    if (member.Any())
                    {
                        foreach (var item in member)
                        {
                            var data = new GroupMember();
                          

                            data.MemberID = item;
                            data.JoinDate = DateTime.UtcNow;

                            data.GroupId = Id;

                            conM.InsertOrUpdate(data);
                        }

                    }
                   
                return RedirectToAction("Index","Profile");

            }
            return null;
}
        public ActionResult EditGroup(int id)
        {
            var conn = new RepositoryBaseMongo("FriendList");
            var connG = new RepositoryBaseMongo("Group");
            var connM = new RepositoryBaseMongo("GroupMember");
            var list = conn.GetAll<FriendList>().Where(x => x.MyId == userId || x.FriendId == userId).ToList();
            var group = connG.GetAll<Group>().FirstOrDefault(x => x.GroupId == id);
            ViewBag.Selected = connM.GetAll<GroupMember>().Where(x => x.GroupId == id).Select(x => x.MemberID.ToString()).ToList();
          

            ViewBag.FriendList = new SelectList(list, "MyId", "FriendId");
            
         
            return View (group);

        }
        [HttpPost]
        public ActionResult AddGroupMember(int GroupId, int? member)
        {
            if (member != null)
            {
                var conM = new RepositoryBaseMongo("GroupMember");
                var members = new GroupMember();
                members.GroupId = GroupId;

                members.MemberID = Convert.ToInt32(member);
                members.JoinDate = DateTime.UtcNow;
                conM.InsertOrUpdate(members);
                return RedirectToAction("Group", new { groupId = GroupId });
                
            }
            else
            {
                return null;
            }
           
        }

       
        public ActionResult RemoveGroup(int groupId)
        {
            var conM = new RepositoryBaseMongo("GroupMember");
            var members = conM.GetAll<GroupMember>().FirstOrDefault(x=>x.GroupId==groupId && x.MemberID==userId);

            conM.Delete<GroupMember>(members);
            return RedirectToAction("Index", "Profile");
            
        } 
        [HttpPost]
        public ActionResult EditGroup(Group group, List<int> member)
        {
            if (ModelState.IsValid)
            {
                var connection = new RepositoryBaseMongo("Group");
           
                var list =
                    connection.GetAll<Group>()
                        .FirstOrDefault(x => x.GroupId == group.GroupId);

                list.Type = group.Type;
                list.GroupName = group.GroupName;
              
                connection.InsertOrUpdate(list);

              
                // members post
                var conM = new RepositoryBaseMongo("GroupMember");
                var delete =
                    conM.GetAll<GroupMember>().Where(x => x.GroupId == group.GroupId && x.MemberID != userId).ToList();
                if (delete.Any())
                {
                    foreach (var de in delete)
                    {
                        conM.Delete<GroupMember>(de);
                    }
                }
                


                if (member.Any())
                {
                    foreach (var item in member)
                    {
                        var data = new GroupMember();


                        data.MemberID = item;
                        data.JoinDate = DateTime.UtcNow;

                        data.GroupId = group.GroupId;

                        conM.InsertOrUpdate(data);
                    }

                }

                return RedirectToAction("Group", new {groupId=group.GroupId});

            }
            return null;
        }

        public ActionResult GroupDelete(int Id)
        {
            var con = new RepositoryBaseMongo("Group");
            List<Group> list = (from f in con.GetAll<Group>()
                                     where f.GroupId == Id
                                     select f).ToList();
            Group group = new Group();
            if (list.Count > 0) group = list[0];
            con.Delete<Group>(group._id);
            return RedirectToAction("Group");

        }
       





    }
}

